//
//  iOsirisViewController.m
//  iOsiris
//
//  Created by bram on 12/12/10.
//  Copyright __MyCompanyName__ 2010. All rights reserved.
//

#import "iOsirisViewController.h"
#import "DataLoadingViewController.h"

@implementation iOsirisViewController

@synthesize username;
@synthesize password;


- (IBAction) editDone:(id)sender
{
	[sender resignFirstResponder];
}

- (IBAction) closeKeyboard:(id)sender
{
	[username resignFirstResponder];
	[password resignFirstResponder];
}

- (IBAction) login:(id)sender
{
	// Connect to the database.
	Database *db = [[Database alloc] init];
	
	// Get the account of the given username.
	Account *user = [db getAccountByName:username.text];
	// Check if user exists and when exists check the password.
	if ([user.username isEqualToString:username.text])
	{
		// When user is authenticated, go to next view.
		if ([user.password isEqualToString:password.text])
		{
			// Open the data loading view.
			DataLoadingViewController *dataLoadingViewController = [[DataLoadingViewController alloc] initWithNibName:@"DataLoadingViewController" bundle:nil];
			
			[dataLoadingViewController setUser:user];
			[self.view addSubview:dataLoadingViewController.view];
		}
		else {
			// When user is not authenticated, show message.
			UIAlertView *error = [[UIAlertView alloc] 
			initWithTitle:@"Error" 
			message:@"Failed to login, incorrect credentials!" 
			delegate:nil 
			cancelButtonTitle:@"Ok" 
			otherButtonTitles:nil];
			
			[error show];
			[error release];
		}
	}
	else 
	{
		// When user is not authenticated, show message.
		UIAlertView *error = [[UIAlertView alloc] 
		initWithTitle:@"Error" 
		message:@"Failed to login, incorrect credentials!" 
		delegate:nil 
		cancelButtonTitle:@"Ok" 
		otherButtonTitles:nil];
		
		[error show];
		[error release];
	}

	// Release user account.
	[user release];
	// Close database
	[db closeDatabase];
	// Release database
	[db release];
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}

@end
